<template>
  <div class="p-3">
    <a-card style="height: 820px" :bordered="false">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="收费期">
          <a-date-picker v-model:value="searchForm.year" picker="year" />
        </a-form-item>
        <a-form-item label="归属机构">
          <a-tree-select
            v-model:value="searchForm.belongComId"
            tree-node-filter-prop="label"
            style="width: 150px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            :tree-data="comanyList"
            placeholder="请选择归属机构"
          />
        </a-form-item>
        <a-form-item label="业务类型">
          <a-select
            v-model:value="searchForm.heatType"
            placeholder="请选择业务类型"
          >
            <a-select-option value="1">供热</a-select-option>
            <a-select-option value="2">制冷</a-select-option>
            <a-select-option value="3">供水</a-select-option>
            <a-select-option value="4">光伏</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="收费状态">
          <a-select
            v-model:value="searchForm.chargeStatus"
            placeholder="请选择业务类型"
          >
            <a-select-option value="1">已交清</a-select-option>
            <a-select-option value="2">部分交</a-select-option>
            <a-select-option value="3">未交</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="onSearch">查询</a-button>
        </a-form-item>
        <a-form-item>
          <a-button type="primary">重置</a-button>
        </a-form-item>
        <a-button
          type="primary"
          :icon="h(HistoryOutlined)"
          class="mr-3"
          @click="onHistory"
          >导出历史</a-button
        >
        <a-button
          type="primary"
          :icon="h(ReconciliationOutlined)"
          class="mr-3"
          @click="onExport"
          >导出信息</a-button
        >
      </a-form>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        bordered
        :pagination="pagination"
        class="mt-5"
        :scroll="{ y: 600 }"
      >
      </a-table>
    </a-card>
    <a-modal
      title="导出历史"
      :visible="showHistory"
      @cancel="onCancel"
      width="1400px"
    >
      <a-table
        :columns="historyColumns"
        :data-source="historyDataSource"
        bordered
        :pagination="historyPagination"
        class="mt-5"
        :row-class-name="
          (_record: any, index: number) =>
            index % 2 === 1 ? 'table-striped' : null
        "
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'states'">
            <a-tag :bordered="false" color="success" v-if="record.states == '0'"
              >完成</a-tag
            >
            <a-tag :bordered="false" color="error" v-else>失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, h } from 'vue';
import {
  SearchOutlined,
  RedoOutlined,
  HistoryOutlined,
  ReconciliationOutlined,
} from '@ant-design/icons-vue';
import {
  getAreaSummaryApi,
  getAreaSummaryExportApi,
  getHeatInspectionExportHistoryApi,
} from '#/api/core/statistical';
import { message } from 'ant-design-vue';
import { getCompanyTree } from '#/api/core/develop';
import dayjs from 'dayjs';

const historyPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    onHistory();
  },
});
const showHistory = ref(false);
const historyDataSource = ref([]);
const searchForm = reactive({
  year: '',
  maxCapacity: '',
  minCapacity: '',
  heatType: undefined,
  belongComId: undefined,
  chargeStatus: undefined,
});
const columns = [
  {
    title: '归属机构',
    dataIndex: 'companyName',
    key: 'companyName',
    align: 'center',
  },
  {
    title: '项目',
    dataIndex: 'heatExchangeStationName',
    key: 'heatExchangeStationName',
    align: 'center',
  },
  {
    title: '供暖能力',
    dataIndex: 'feeRate',
    key: 'feeRate',
    align: 'center',
  },
  {
    title: '建筑面积',
    dataIndex: 'buildingArea',
    key: 'buildingArea',
    align: 'center',
  },
  {
    title: '应收全费面积',
    dataIndex: 'ysqfArea',
    key: 'ysqfArea',
    align: 'center',
  },
  {
    title: '应收全费金额',
    dataIndex: 'ysqfMoney',
    key: 'ysqfMoney',
    align: 'center',
  },
  {
    title: '应收基本费面积',
    dataIndex: 'ysjbfArea',
    key: 'ysjbfArea',
    align: 'center',
  },
  {
    title: '应收基本费金额',
    dataIndex: 'ysjbfMoney',
    key: 'ysjbfMoney',
    align: 'center',
  },
  {
    title: '实收基本费面积',
    dataIndex: 'ssjbfArea',
    key: 'ssjbfArea',
    align: 'center',
  },
  {
    title: '实收基本费折算面积',
    dataIndex: 'ssjbfzsArea',
    key: 'ssjbfzsArea',
    align: 'center',
  },
  {
    title: '实收基本费金额',
    dataIndex: 'ssjbfArea',
    key: 'ssjbfArea',
    align: 'center',
  },
];
const historyColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    align: 'center',
  },
  {
    title: '操作日期',
    dataIndex: 'createTime',
    key: 'createTime',
    align: 'center',
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'createPersonName',
    key: 'createPersonName',
    align: 'center',
  },
  {
    title: '机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'isOk',
    key: 'isOk',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
  },
];
const dataSource = ref([]);
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onSearch = () => {
  const query = {
    page: pagination.current,
    limit: pagination.pageSize,
    year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
    maxCapacity: searchForm.maxCapacity ?? '',
    minCapacity: searchForm.minCapacity ?? '',
    heatType: searchForm.heatType ?? undefined,
    belongComId: searchForm.belongComId ?? undefined,
    chargeStatus: searchForm.chargeStatus ?? undefined,
  };
  getAreaSummaryApi(query).then((res: any) => {
    console.log(res);
    dataSource.value = res.data.data;
    pagination.total = res.data.total;
  });
};
const onExport = () => {
  const query = {
    year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
    maxCapacity: searchForm.maxCapacity ?? '',
    minCapacity: searchForm.minCapacity ?? '',
    heatType: searchForm.heatType ?? undefined,
    belongComId: searchForm.belongComId ?? undefined,
    chargeStatus: searchForm.chargeStatus ?? undefined,
  };
  getAreaSummaryExportApi(query).then((res: any) => {
    console.log('导出信息', res);
    if (res.data.code === 200) {
      message.success('导出成功');
    } else {
      message.error('导出失败');
    }
  });
};
const comanyList = ref([]);
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      console.log(tree);
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};
getTableData();
const onHistory = () => {
  showHistory.value = true;
  const query = {
    page: historyPagination.current,
    limit: historyPagination.pageSize,
    fileType: '年度区域汇总表',
  };
  getHeatInspectionExportHistoryApi(query).then((res: any) => {
    console.log('导出历史', res);
    if (res.data.code === 200) {
      historyDataSource.value = res.data.data;
      historyPagination.total = res.data.total;
    }
  });
};
const onCancel = () => {
  showHistory.value = false;
};
const onDown = (e: any) => {
  // console.log(e);
  const loading = message.loading({
    content: "下载中...",
    duration: 0,
  });

  try {
    // 下载地址拼接
    const url = e.urlAddress;

    // 使用a标签下载，避免X-Frame-Options错误
    const link = document.createElement("a");
    link.href = url;
    link.download = ""; // 触发下载而不是导航
    link.target = "_blank";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 关闭loading
    setTimeout(() => {
      loading();
    }, 1000);
  } catch (error) {
    console.error("下载出错:", error);
    message.error("下载出错，请重试");
    loading();
  }
};
</script>
<style scoped></style>
